import { type PaginationProps } from "@pureadmin/table";
import { emitter } from "@/utils/mitt";
import { ref, computed, Transition, reactive, onMounted, nextTick, watch, onBeforeUnmount } from "vue";
import {
  FunDataGetFundDataByType,
  FunDataCalculatedRateOfReturn
} from "@/api/stu/Cecurity";
import { useRoute } from "vue-router";
import CloseFill from "@iconify-icons/ri/close-fill";
import AddFill from "@iconify-icons/ri/add-fill";
import { ElMessage } from "element-plus";
import { Pie } from '@antv/g2plot';
export function useInvestment(prop) {
  const route = useRoute();
  const Visible = ref(false);
  const red = "{color:red;}"
  const zzsreg = /^\+?[1-9][0-9]*$/;
  //现金管理类的表单
  const columns1: TableColumnList = [
    {
      label: "选择",
      prop: "select",
      width: 50,
      cellRenderer: ({ row }) => (
        <iconify-icon-offline class="myicon" icon={AddFill} />
      )
    }, {
      label: "序号",
      type: "index",
    },
    {
      label: "基金代码",
      prop: "fundCode"
    },
    {
      label: "基金简称",
      prop: "fundName",
    },
    {
      label: "日期",
      prop: "fundDate"
    },
    {
      label: "万份收益",
      prop: "manyProfit",
      cellRenderer: ({ row }) => (`${(row.manyProfit).toFixed(2)}`)
    },

    {
      label: "年化收益类",
      prop: "",
      children: [
        {
          label: "7日",
          prop: "sevenProfit",
          cellRenderer: ({ row }) => (`${(row.sevenProfit).toFixed(2)}%`)
        },
        {
          label: "14日",
          prop: "fourteenProfit",
          cellRenderer: ({ row }) => (`${(row.fourteenProfit).toFixed(2)}%`)
        }, {
          label: "28日",
          prop: "twentyEight",
          cellRenderer: ({ row }) => (`${(row.twentyEight).toFixed(2)}%`)
        }
      ]
    },
    {
      label: "净值",
      prop: "netValue"
    },
    {
      label: "近一月",
      prop: "near1Month",
      cellRenderer: ({ row }) => (
        <text style={row.near1Month > 0 ? 'color:red' : 'color:green'}> {(row.near1Month).toFixed(2)}%</text>
      )
    },
    {
      label: "近三月",
      prop: "near3Month",
      cellRenderer: ({ row }) => (<text style={row.near3Month > 0 ? 'color:red' : 'color:green'}> {(row.near3Month).toFixed(2)}%</text>)
    },
    {
      label: "近六月",
      prop: "near6Month",
      cellRenderer: ({ row }) => (<text style={row.near6Month > 0 ? 'color:red' : 'color:green'}> {(row.near6Month).toFixed(2)}%</text>)
    },
    {
      label: "近一年",
      prop: "near1Years",
      cellRenderer: ({ row }) => (<text style={row.near1Years > 0 ? 'color:red' : 'color:green'}> {(row.near1Years).toFixed(2)}%</text>)
    },
    {
      label: "近二年",
      prop: "near2Years",
      cellRenderer: ({ row }) => (<text style={row.near2Years > 0 ? 'color:red' : 'color:green'}> {(row.near2Years).toFixed(2)}%</text>)
    },
    {
      label: "近三年",
      prop: "near3Years",
      cellRenderer: ({ row }) => (<text style={row.near3Years > 0 ? 'color:red' : 'color:green'}> {(row.near3Years).toFixed(2)}%</text>)
    },
    {
      label: "今年来",
      prop: "dayOfYear",
      cellRenderer: ({ row }) => (<text style={row.dayOfYear > 0 ? 'color:red' : 'color:green'}> {(row.dayOfYear).toFixed(2)}%</text>)
    },
    {
      label: "成立来",
      prop: "setUp",
      cellRenderer: ({ row }) => (<text style={row.setUp > 0 ? 'color:red' : 'color:green'}> {(row.setUp).toFixed(2)}%</text>)
    },
    {
      label: "手续费",
      prop: "serviceRate",
      cellRenderer: ({ row }) => (`${(row.serviceRate).toFixed(2)}%`)
    }

  ];
  // 固定收益-权益收益-另类收益
  const columns: TableColumnList = [
    {
      label: "选择",
      prop: "select",
      width: 50,
      cellRenderer: ({ row }) => (
        <iconify-icon-offline class="myicon" icon={AddFill} />
      )
    },
    {
      label: "序号",
      type: "index",
    },
    {
      label: "基金代码",
      prop: "fundCode"
    },
    {
      label: "基金简称",
      prop: "fundName",
    },
    {
      label: "日期",
      prop: "fundDate"
    },
    {
      label: "单位净值",
      prop: "averageNAV"
    }, {
      label: "累积净值",
      prop: "accumulatedNet",
      cellRenderer: ({ row }) => (<text style={row.accumulatedNet > 0 ? 'color:red' : 'color:green'}> {(row.accumulatedNet).toFixed(2)}%</text>)
    },
    {
      label: "日增长率",
      prop: "dailyGrowthRate",
      cellRenderer: ({ row }) => (<text style={row.dailyGrowthRate > 0 ? 'color:red' : 'color:green'}> {(row.dailyGrowthRate).toFixed(2)}%</text>)
    },
    {
      label: "近一周",
      prop: "near1Week",
      cellRenderer: ({ row }) => (<text style={row.near1Week > 0 ? 'color:red' : 'color:green'}> {(row.near1Week).toFixed(2)}%</text>)
    },
    {
      label: "近一月",
      prop: "near1Month",
      cellRenderer: ({ row }) => (
        <text style={row.near1Month > 0 ? 'color:red' : 'color:green'}> {(row.near1Month).toFixed(2)}%</text>
      )
    },
    {
      label: "近三月",
      prop: "near3Month",
      cellRenderer: ({ row }) => (<text style={row.near3Month > 0 ? 'color:red' : 'color:green'}> {(row.near3Month).toFixed(2)}%</text>)
    },
    {
      label: "近六月",
      prop: "near6Month",
      cellRenderer: ({ row }) => (<text style={row.near6Month > 0 ? 'color:red' : 'color:green'}> {(row.near6Month).toFixed(2)}%</text>)
    },
    {
      label: "近一年",
      prop: "near1Years",
      cellRenderer: ({ row }) => (<text style={row.near1Years > 0 ? 'color:red' : 'color:green'}> {(row.near1Years).toFixed(2)}%</text>)
    },
    {
      label: "近二年",
      prop: "near2Years",
      cellRenderer: ({ row }) => (<text style={row.near2Years > 0 ? 'color:red' : 'color:green'}> {(row.near2Years).toFixed(2)}%</text>)
    },
    {
      label: "近三年",
      prop: "near3Years",
      cellRenderer: ({ row }) => (<text style={row.near3Years > 0 ? 'color:red' : 'color:green'}> {(row.near3Years).toFixed(2)}%</text>)
    },
    {
      label: "今年来",
      prop: "dayOfYear",
      cellRenderer: ({ row }) => (<text style={row.dayOfYear > 0 ? 'color:red' : 'color:green'}> {(row.dayOfYear).toFixed(2)}%</text>)
    },
    {
      label: "成立来",
      prop: "setUp",
      cellRenderer: ({ row }) => (<text style={row.setUp > 0 ? 'color:red' : 'color:green'}> {(row.setUp).toFixed(2)}%</text>)
    },
    {
      label: "手续费",
      prop: "serviceRate",
      cellRenderer: ({ row }) => (`${(row.serviceRate).toFixed(2)}%`)
    }
  ];
  // 已选基金表头
  const columns3: TableColumnList = [
    {
      label: "删除",
      fixed: "left",
      width: 50,
      slot: "operation"
    },
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "基金类型",
      prop: "fundName",
      cellRenderer: ({ row }) => (
        <span>
          {row.funDataType === '1' ? '现金管理类' :
            row.funDataType === '2' ? '固定收益类' :
              row.funDataType === '3' ? '权益收益类' : "另类及其他"
          }
        </span>
      )
    }, {
      label: "基金代码",
      prop: "fundCode"
    }, {
      label: "基金名称",
      prop: "fundName"
    }, {
      label: "投资比例(%)",
      prop: "ProportionOfInvestment",
      cellRenderer: ({ row, index }) => (
        <el-input size="small" type='number' min={0} v-model={row.ProportionOfInvestment} />
      )
    }
  ];

  // TODO:选中的列表数据
  const portfolioldId = ref('');
  const num_there = ref<number>(0);// TODO:模拟年化收益率
  const productOne = ref<number>(0);// TODO:单个产品预期波动率
  const reffrom = ref();
  const SeleteData = ref([]);
  const dataList = ref();
  const loading = ref<boolean>(false);
  const dataList2 = ref();
  const loading2 = ref<boolean>(false);
  const dataList3 = ref();
  const loading3 = ref<boolean>(false);
  const dataList4 = ref();
  const loading4 = ref<boolean>(false);
  const dataList5 = ref([]);
  const loading5 = ref<boolean>(false);
  const form = reactive<any>({
    yearsyield: 0,//年化利率
    yerasvolatility: 0,// 年化波动率
    fromLv: "", //等级
    name: "", // 名称
    date: ""//持有日期
  })
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100],
    background: true
  });
  const pagination3 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100],
    background: true
  });
  const pagination4 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 50, 100],
    background: true
  });
  const rules = {
    fromLv: [{ required: true, message: "请输入等级", trigger: "blur" }],
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    date: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (value < 1 || !zzsreg.test(value)) {
            return callback(new Error('不能小于一个月且是整数'))
          } else if (value > 24) {
            return callback(new Error('不能大于二十四个月'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
      // {
      // required: true, message: "请输入有效日期", trigger: "blur"
      // }
    ],
  }
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }

  // 分页方法
  function handleSizeChange(val) {
    getCashManagement1()
  }

  function handleCurrentChange(val) {
    getCashManagement1()
  }

  function handleSizeChange2(val) {
    getCashManagement2()
  }

  function handleCurrentChange2(val) {
    getCashManagement2()
  }

  function handleSizeChange3(val) {
    getCashManagement3()
  }

  function handleCurrentChange3(val) {
    getCashManagement3()
  }

  function handleSizeChange4(val) {
    getCashManagement4()
  }

  function handleCurrentChange4(val) {
    getCashManagement4()
  }


  // 分页end

  // 选择模拟数据
  function AddSeleteData(row, column, event) {
    if (dataList5.value.length >= 10) {
      ElMessage.warning("最多选择10条数据")
      return
    }
    if (!dataList5.value.some(r => r.fundCode === row.fundCode)) {
      dataList5.value.push(row);
    }
  }
  // 删除选择模拟数据
  // function DeleteSeleteData(row, column, event) {

  //   if (!column.no) {
  //     dataList5.value = dataList5.value.filter(item => item.fundId !== row.fundId)
  //   }
  //   // 调用组件删除时 更新prop
  //   if (portfolioldId.value) {
  //     emitter.emit("updatePropData", dataList5.value)
  //   }
  // }

  function DeleteSeleteData(row) {
    dataList5.value = dataList5.value.filter(item => item.fundId !== row.fundId)
    row.ProportionOfInvestment = "";
    // // 调用组件删除时 更新prop
    if (portfolioldId.value) {
      emitter.emit("updatePropData", dataList5.value)
    }
  }
  // 获取现金管理类
  async function getCashManagement1() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
      fundType: "1"
    };
    const res = await FunDataGetFundDataByType(data);
    if (res.success) {
      dataList.value = res.data.fundData
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.message)
    }
  }
  async function getCashManagement2() {
    const data = {
      pageIndex: pagination2.currentPage,
      pageCount: pagination2.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
      fundType: "2"
    };
    const res = await FunDataGetFundDataByType(data);
    if (res.success) {
      dataList2.value = res.data.fundData
      pagination2.total = res.data.totalCount
    } else {
      ElMessage.error(res.message)
    }
  }
  async function getCashManagement3() {
    const data = {
      pageIndex: pagination3.currentPage,
      pageCount: pagination3.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
      fundType: "3"
    };
    const res = await FunDataGetFundDataByType(data);
    if (res.success) {
      dataList3.value = res.data.fundData
      pagination3.total = res.data.totalCount
    } else {
      ElMessage.error(res.message)
    }
  }
  async function getCashManagement4() {
    const data = {
      pageIndex: pagination4.currentPage,
      pageCount: pagination4.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
      fundType: "4"
    };
    const res = await FunDataGetFundDataByType(data);
    if (res.success) {
      dataList4.value = res.data.fundData
      pagination4.total = res.data.totalCount
    } else {
      ElMessage.error(res.message)
    }
  }
  // 获取现金管理类 end
  // 试算模拟
  function TrialSimulation() {
    let arry = [];
    let num_theres = 0;//模拟年利率化
    let AllproductOnesArry = [];
    let PJNums = 0;
    let AllproductOnes = 0;
    let allproduct = true;
    dataList5.value.forEach((item) => {
      let productOnes = 0;
      if (item.ProportionOfInvestment === undefined || item.ProportionOfInvestment === "") {
        allproduct = false
        return;
      };

      if (item.ProportionOfInvestment < 0) {
        ElMessage.error("投资比例不能小于0");
        allproduct = false
        return;
      }

      //new
      // //模拟年化收益率= 过去三年平均收益率《近三年收益率/3)*投资比例
      const new3Years = item.near1Years + item.near2Years + item.near3Years
      num_theres += Number(new3Years) / 3 * (Number(item.ProportionOfInvestment) / 100)
      /* --------------------------------------- */
      //2.单个产品预期波动率 =
      //（（（第一年的收益率 - 过去三年平均收益率）^ 2）/ 2）^(1 / 2) +
      //（（（第二年的收益率 - 过去三年平均收益率）^ 2）/ 2）^(1 / 2) +
      //（（（第三年的收益率 - 过去三年平均收益率）^ 2）/ 2）^(1 / 2)
      productOnes =
        Math.pow(((Math.pow((item.near1Years - (new3Years / 3)), 2)) / 2), (1 / 2)) +
        Math.pow(((Math.pow((item.near2Years - (new3Years / 3)), 2)) / 2), (1 / 2)) +
        Math.pow(((Math.pow((item.near3Years - (new3Years / 3)), 2)) / 2), (1 / 2));
      AllproductOnesArry.push(productOnes)

      AllproductOnes += Math.pow(productOnes * Number(item.ProportionOfInvestment), 2);
      // // 计算总和 100
      arry.push(Number(item.ProportionOfInvestment));
    });
    if (!allproduct) {
      ElMessage.warning("请输入投资比例");
      return
    };
    // 波动率总和
    const VolatilitySummation = AllproductOnesArry.reduce((total, current) => total + current, 0);
    // 波动率平均值
    const MeanValue = VolatilitySummation / AllproductOnesArry.length;
    let AllVariance = 0; //
    // 波动率方差
    AllproductOnesArry.forEach(el => {
      // 单个波动率 - 平均波动率 ^ 2
      AllVariance += Math.pow(el - MeanValue, 2)
    });
    // 预期波动率 = 标准差
    const ExpectedVolatility = Math.sqrt(AllVariance / AllproductOnesArry.length)


    form.yearsyield = Number(num_theres.toFixed(2)); // 收益率
    form.yerasvolatility = ExpectedVolatility.toFixed(2); // 波动率
    const sum = arry.reduce((total, current) => total + current, 0);

    if (sum !== 100) {
      ElMessage.warning(`输入总比例值${sum > 100 ? '已超' : '未达到'}100%`);
      allproduct = false
      return
    }
    if (!allproduct) return;
    Visible.value = allproduct
    nextTick(() => {
      ShowAntvG2Pie()
    })
  }
  // 饼图
  function ShowAntvG2Pie() {
    let data = [];
    let arr1 = [];
    let arr2 = [];
    let arr3 = [];
    let arr4 = [];

    dataList5.value.forEach((item) => {
      const ProportionOfInvestment = Number(item.ProportionOfInvestment);
      switch (item.funDataType) {
        case '1':
          arr1.push(ProportionOfInvestment);
          break;
        case '2':
          arr2.push(ProportionOfInvestment);
          break;
        case '3':
          arr3.push(ProportionOfInvestment);
          break;
        case '4':
          arr4.push(ProportionOfInvestment);
          break;
      }
    });
    const sum1 = arr1.reduce((total, current) => total + current, 0);
    const sum2 = arr2.reduce((total, current) => total + current, 0);
    const sum3 = arr3.reduce((total, current) => total + current, 0);
    const sum4 = arr4.reduce((total, current) => total + current, 0);
    data = [
      {
        type: '现金管理类',
        value: sum1
      },
      {
        type: '固定收益类',
        value: sum2
      },
      {
        type: '权益收益类',
        value: sum3
      },
      {
        type: '另类及其他',
        value: sum4
      }
    ];
    const piePlot = new Pie('visible_pie', {
      appendPadding: 15,
      data,
      angleField: 'value',
      colorField: 'type',
      radius: 1,
      innerRadius: 0.60,
      meta: {
        value: {
          formatter: (v) => ` ${v}%`,
        },
      },
      label: {
        type: 'inner',
        offset: '-50%',
        autoRotate: false,
        style: { textAlign: 'center' },
        formatter: ({ percent }) => `${(percent * 100).toFixed(0)}%`,
      },
      statistic: {
        title: {
          content: '组合配比',
          offsetY: -8,
          style: {
            fontSize: '12',
            fontWeight: 400,
          },

        },
        content: {
          offsetY: -4,
          content: '',
          style: {
            fontSize: '12',
            fontWeight: 400,
          },
        }
      },
      interactions: [
        { type: 'element-selected' },
        { type: 'element-active' },
        {
          type: 'pie-statistic-active',
          cfg: {
            start: [
              { trigger: 'element:mouseenter', action: 'pie-statistic:change' },
              { trigger: 'legend-item:mouseenter', action: 'pie-statistic:change' },
            ],
            end: [
              { trigger: 'element:mouseleave', action: 'pie-statistic:reset' },
              { trigger: 'legend-item:mouseleave', action: 'pie-statistic:reset' },
            ],
          },
        },
      ],

    });

    piePlot.render();
  }

  function stubimfrom(row) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        "planId": route.query.planId,
        "taskId": route.query.taskId,
        portfolioId: portfolioldId.value,//为空则为新建资产组合 ，不为空则修改《一键优化)
        portfolioldName: form.name, // TODO:名称
        riskGrade: form.fromLv, // TODO: 类型
        recommendedHold: form.date, // TODO:持有期限
        annualYield: form.yearsyield, // TODO:年化收益率
        annualizedVolatility: form.yerasvolatility, // TODO:年化波动率
        fundJson: JSON.stringify(dataList5.value), // 选中的列表数据
        positionVolatility: "",
        positionYield: ""
      };
      BtnLoading.value = true
      OUTBtnLoding()
      const res = await FunDataCalculatedRateOfReturn(data);
      if (res.success) {
        ElMessage.success(res.msg)
        closefrom(row)
        dataList5.value.forEach(item => item.ProportionOfInvestment = '');
        dataList5.value = [];
        if (portfolioldId.value) {
          // 清空调用此组件的父组件传给此组件的值
          // 更新 PortfolioRebalancings 页面数据
          emitter.emit("updatePortList")
          dataList5.value = [];
          portfolioldId.value = "";
        }
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  watch(prop, newval => {
    dataList5.value = newval.PropData;
    portfolioldId.value = newval.portfolioldId;
  }, { immediate: true })

  // 关闭弹窗
  function closefrom(row) {
    Visible.value = false;
    // 手动清空选中的基金列表
    row.resetFields()
  }


  onBeforeUnmount(() => {
    dataList5.value = [];
    portfolioldId.value = "";
    emitter.off("updatePortList")
  })

  onMounted(() => {
    getCashManagement1()
    getCashManagement2()
    getCashManagement3()
    getCashManagement4()
  })

  return {
    form,
    rules,
    reffrom,
    Visible,
    columns,
    columns1,
    num_there,
    productOne,
    SeleteData,
    dataList,
    loading,
    pagination,
    dataList2,
    loading2,
    pagination2,
    columns3,
    dataList3,
    loading3,
    dataList4,
    loading4,
    dataList5,
    loading5,
    BtnLoading,
    pagination3,
    pagination4,
    portfolioldId,
    closefrom,
    stubimfrom,
    DeleteSeleteData,
    AddSeleteData,
    TrialSimulation,
    handleSizeChange,
    handleCurrentChange,
    handleSizeChange2,
    handleCurrentChange2,
    handleSizeChange3,
    handleCurrentChange3,
    handleSizeChange4,
    handleCurrentChange4
  }
}
